import React from 'react';
import { Menu } from 'antd';
import { useSelector, useDispatch } from 'react-redux';
import { setCollapse } from '@/store/global';
import type { RootState } from '@/store';
import type { IRouter } from '@/router/router.d';
import { MenuFoldOutlined, MenuUnfoldOutlined } from '@ant-design/icons';
import { useLocation, useHistory } from "react-router-dom";
import { Icon } from '@/components';
import './index.scss';

const { SubMenu } = Menu;


const NavBar: React.FC = () => {
  const { isCollapse, routers, flattenRouters } = useSelector((state: RootState) => state.global);
  const dispatch = useDispatch();
  // 切换侧边栏打开状态
  const toggleCollapse = () => {
    dispatch(setCollapse(!isCollapse))
  }

  const History = useHistory();
  const Location = useLocation();

  // 点击menu跳转路由
  const handleClickMenu = (e: any) => {
    if (Location.pathname !== e.key) History.push(e.key)
  }

  // 递归渲染menu
  const DeepRenderMenu: React.FC = (route: any) => {
    // 查看当前路由是否有子级 如果有过滤掉不在menu下显示的路由
    let childrenData: IRouter[] = route.children ? route.children.filter((item: IRouter) => !item.hidden) : [];
    // 如果子集菜单数量大于0则显示subMenu 反正直接返回 item
    if (childrenData.length > 0) {
      const childFirstRoute = childrenData[0];
      const grandchildData = childFirstRoute.children ? childFirstRoute.children.filter((item: IRouter) => !item.hidden) : [];
      // 如果alwaysShow不成立并且只有一个子则直接返回menu.Item 反之则返回一个SubMenu 并递归子级
      if (childrenData.length <= 1 && !route.alwaysShow && grandchildData.length < 1) {
        // 查看当前是否存在孙子级如果存在则递归
        return <Menu.Item icon={childFirstRoute.meta?.icon?<Icon type={childFirstRoute.meta.icon} />:null} key={childFirstRoute.path}>{childFirstRoute.meta?.title}</Menu.Item>
      } else {
        return <SubMenu key={route.path} icon={route.meta?.icon?<Icon type={route.meta.icon} />:null} title={route.meta?.title}>
          {
            childrenData.map((item: object) => DeepRenderMenu(item))
          }
        </SubMenu>
      }
    } else {
      return <Menu.Item icon={route.meta?.icon?<Icon type={route.meta.icon} />:null} key={route.path}>{route.meta?.title}</Menu.Item>
    }
  }
  // 获取当前所在路由信息
  const currentRoute = flattenRouters.filter((route: IRouter) => route.path === Location.pathname)[0];
  const currentPaht = currentRoute?.meta?.activeMenu || Location.pathname;

  // 当前默认展开菜单
  const pathArray: Array<string> = currentPaht.split('/');
  const currentOpenMenuKyes = pathArray.map((item: any, index: number) => {
    return pathArray.reduce((oldVal: string, currVal: string, currInx: number): any => {
      return oldVal + (index <= currInx ? '' : `/${currVal}`)
    })
  });

  // 通过path查询路由表中的配置
  return (
    <>
      <div className={`hi-layout-sider ${isCollapse ? 'hide' : ''}`}></div>
      <aside className={`hi-layout-sider sider-fixed ${isCollapse ? 'hide' : ''}`}>
        <div className="hi-layout-menu-content">
          <Menu
            defaultOpenKeys={currentOpenMenuKyes}
            selectedKeys={[currentPaht]}
            defaultSelectedKeys={[currentPaht]}
            inlineCollapsed={isCollapse}
            onClick={handleClickMenu}
            inlineIndent={16}
            style={{ width: 'calc(100% - 2px)' }}
            mode="inline"
            className="hi-global-sider-menu"
          >
            {routers.filter((item: any) => item.hidden !== false).map((item: any) => DeepRenderMenu(item))}
          </Menu>
        </div>
        <div className="hi-sider-links" onClick={toggleCollapse}>
          {isCollapse ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
        </div>
      </aside>
    </>
  )
}

export default NavBar
